package net.suncapper.wcss.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.suncapper.wcss.common.JsonResponse;
import net.suncapper.wcss.common.utls.SessionUtils;
import net.suncapper.wcss.model.domain.*;
import net.suncapper.wcss.mapper.ApplicationMapper;
import net.suncapper.wcss.model.dto.PageDTO;
import net.suncapper.wcss.model.vo.ApplicationVO;
import net.suncapper.wcss.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static net.suncapper.wcss.common.BaseConstant.*;

/**
 * <p>
 * 申请表 服务实现类
 * </p>
 *
 * @author ztr
 * @since 2025-11-11
 */
@Service
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, Application> implements IApplicationService {
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private IKnrdService knrdService;
    @Autowired
    private IBatchSettingService batchSettingService;
    @Autowired
    private IStudentDataService studentDataService;
    @Autowired
    private IRoleFlowSettingService roleFlowSettingService;
    @Autowired
    private IAuditHistoryService auditHistoryService;
    @Override
    public JsonResponse submit(Application application) {
        WhitelistSetting user = SessionUtils.getCurrentLoginUser();
        List<Knrd> list = knrdService.list(Wrappers.<Knrd>lambdaQuery().eq(Knrd::getStudentId, user.getSn()));
        if (CollectionUtils.isEmpty(list)) {
            return JsonResponse.failure("该生不在困难库");
        }
        Knrd knrd = list.getFirst();
        BatchSetting batchSettings = batchSettingService.getOne(Wrappers.<BatchSetting>lambdaQuery().eq(BatchSetting::getActive, 1));
        if (diffeq(knrd, batchSettings)) {
return JsonResponse.failure("该生不符合困难等级级别");
        }
        StudentData studentData = studentDataService.getOne(Wrappers.<StudentData>lambdaQuery().eq(StudentData::getSn, user.getSn()));
        RoleFlowSetting flowSetting = roleFlowSettingService.getOne(Wrappers.<RoleFlowSetting>lambdaQuery().isNull(RoleFlowSetting::getPreNode));

        application.setApplyDate(LocalDate.now())
                .setSn(user.getSn())
                .setName(user.getName())
                .setClassName(studentData.getClazz())
                .setClassSn(studentData.getClassCode())
                .setMajorName(studentData.getMajor())
                .setMajorSn(studentData.getMajorCode())
                .setCollegeName(studentData.getCollege())
                .setCollegeSn(studentData.getCollegeCode())
                .setGender(studentData.getGender())
                .setDifficultyLevel(knrd.getPovertyLevel())
                .setCurrentNodeCode(flowSetting.getNodeCode())
                .setStatus(AUDIT_STATUS_DSH);
        return JsonResponse.success(super.save(application));
    }


    @Override
    public Page<ApplicationVO> getlist(ApplicationVO application, PageDTO pageDTO, WhitelistSetting currentLoginUser) {
        // 1. 创建MyBatis-Plus的Page对象（传入页码和页大小）
        Page<ApplicationVO> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());

        // 2. 调用Mapper，传入page对象，插件会自动处理分页和total计算
        IPage<ApplicationVO> resultPage = applicationMapper.selectByList(page, application, currentLoginUser);

        // 3. 直接返回结果（已包含正确的records和total）
        return (Page<ApplicationVO>) resultPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResponse updateByIds(ApplicationVO application) {
        WhitelistSetting user = SessionUtils.getCurrentLoginUser();
     Application application1 = super.getById(application.getId());
        RoleFlowSetting node = roleFlowSettingService.getNode(application.getCurrentNodeCode());
     if (application1 == null) {
         return JsonResponse.failure("申请不存在");
     }
     if(AUDIT_STATUS_BTG.equals(application.getStatus())){
        application.setStatus(application.getStatus());
        application.setAuditComment(application.getAuditComment());
        application.setCurrentNodeCode(0);
     }else
     {

       if(Objects.nonNull(node.getNextNode())){
          application.setCurrentNodeCode(node.getNextNode());
       }else {
           application.setStatus(application.getStatus());
           Integer nodeCode =0;
           application.setCurrentNodeCode(nodeCode);
       }

     }
     AuditHistory auditHistory = new AuditHistory()
             .setApplicationId(application1.getId())
             .setAuditBy(user.getSn())
             .setAuditorName(user.getName())
             .setAuditNodeCode(node.getNextNode())
             .setAuditNodeName(node.getNodeName())
             .setAuditComment(application.getAuditComment())
             .setStatus(application.getStatus())
                     .setDeleted(false);
     auditHistoryService.save(auditHistory);
        boolean b = super.updateById(application);
        return JsonResponse.success(Map.of(
                "updateSuccess", b,
                "auditSaved", true  // 因事务保证，若走到这里，auditHistory已保存成功
        ));
    }

    private boolean diffeq(Knrd knrd, BatchSetting batchSettings) {
        if (DIFFICULTY_LEVEL_TSKN.equals(batchSettings.getDifficultyLevel())) {
            return DIFFICULTY_LEVEL_TSKN_TXT.equals(knrd.getPovertyLevel());

        } else if (DIFFICULTY_LEVEL_YBKN.equals(batchSettings.getDifficultyLevel())) {
            return DIFFICULTY_LEVEL_TSKN_TXT.equals(knrd.getPovertyLevel())||DIFFICULTY_LEVEL_YBKN_TXT.equals(knrd.getPovertyLevel());
        }

        return false;
    }
}
